import React, { Component } from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
import { Form, Input, Button, message, Checkbox } from 'antd';
import { EMAIL_RE, PORT_RE, URL_RE } from '@util/constants';
import { getEmailConfig, updateEmailConfig } from '@api/email';
import EmailTest from './components/email-test';
import './index.less';

const prefixCls = 'mail-config';
const { Item: FormItem } = Form;
const { Password } = Input;
const formItemLayout = {
  labelCol: {
    span: 5
  },
  wrapperCol: {
    span: 19
  }
};

/* eslint-disable */
function WrappedCheckbox({ value = true, onChange }) {
  return (
    <Checkbox checked={value} onChange={onChange}>
      使用SSL加密（使用加密协议发送邮件更安全）
    </Checkbox>
  );
}
/* eslint-enable */
class MailConfig extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      list: {},
      buttonLoading: false
    };
  }

  componentDidMount() {
    getEmailConfig().then(res => {
      let list = {};
      try {
        list = _.get(res.data, 'data', {});
        // eslint-disable-next-line
      } catch (e) {}
      this.setState({ list }, this.setFieldsValue);
    });
  }

  setFieldsValue() {
    const { list } = this.state;
    const { setFieldsValue } = this.props.form;
    setFieldsValue(list.email_config);
  }

  onClickSubmit = () => {
    const { validateFields } = this.props.form;
    validateFields((errors, values) => {
      if (errors) {
        message.error('有错误，不能提交');
        return;
      }
      this.setState({ buttonLoading: true });
      if (values.prefix === null) {
        delete values.prefix;
      }
      updateEmailConfig(values)
        .then(() => {
          message.success('修改成功');
          this.setState({ buttonLoading: false });
        })
        .catch(error => {
          message.error(error);
          this.setState({ buttonLoading: false });
        });
    });
  };

  setModalVisible = visible => {
    this.setState({ visible });
  };

  validatorServer = (rules, values, callback) => {
    if (!URL_RE.test(values)) {
      return callback('您输入的格式有误');
    }
    return callback();
  };

  render() {
    const {
      form: { getFieldDecorator }
    } = this.props;
    const { visible, buttonLoading } = this.state;
    return (
      <div className={prefixCls}>
        <div className={`${prefixCls}-page-title`}>邮箱配置</div>
        <div className={`${prefixCls}-top-box`}>
          <div className={`${prefixCls}-top-box-item`}>
            <div className={`${prefixCls}-top-box-item-title`}>邮箱协议</div>
            <div className={`${prefixCls}-top-box-item-detail`}>SMTP</div>
          </div>
          <div className={`${prefixCls}-form`}>
            <Form labelAlign="left">
              <FormItem {...formItemLayout} label="邮箱服务器" colon={false}>
                {getFieldDecorator('host', {
                  rules: [
                    {
                      required: true,
                      message: '请输入邮箱服务器'
                    },
                    {
                      validator: this.validatorServer
                    }
                  ],
                  validateFirst: true
                })(<Input placeholder="请输入邮箱服务器地址" />)}
              </FormItem>
              <FormItem {...formItemLayout} label="服务端口" colon={false}>
                {getFieldDecorator('port', {
                  rules: [
                    {
                      required: true,
                      message: '请输入服务端口'
                    },
                    {
                      pattern: PORT_RE,
                      message: '您输入的格式有误'
                    }
                  ]
                })(<Input placeholder="请输入邮箱服务器使用端口" />)}
              </FormItem>
              <FormItem {...formItemLayout} label="邮箱账户" colon={false}>
                {getFieldDecorator('user', {
                  rules: [
                    {
                      required: true,
                      message: '请输入邮箱账户'
                    },
                    {
                      pattern: EMAIL_RE,
                      message: '您输入的格式有误'
                    }
                  ]
                })(<Input placeholder="请输入邮箱账户" />)}
              </FormItem>
              <FormItem {...formItemLayout} label="邮箱密码(或授权码)" colon={false}>
                {getFieldDecorator('password', {
                  rules: [
                    {
                      required: true,
                      message: '请输入邮箱密码(或授权码)'
                    }
                  ]
                })(<Password placeholder="请输入邮箱密码(或授权码)" autoComplete="password" />)}
              </FormItem>
              <FormItem {...formItemLayout} label="&nbsp;&nbsp;&nbsp;安全加密" colon={false}>
                {getFieldDecorator('ssl', {
                  initialValue: true
                })(<WrappedCheckbox />)}
              </FormItem>
              <FormItem {...formItemLayout} label="&nbsp;&nbsp;&nbsp;邮件前缀" colon={false}>
                {getFieldDecorator('prefix', {})(<Input placeholder="自定义收到邮件标题的前缀" />)}
                <div className={`${prefixCls}-form-notes`}>
                  有的服务器为了增加邮箱本身的安全性，给SMTP客户端设置了独立密码，对于开启了独立密码的邮箱，这里的邮箱密码必须用这个独立密码（授权码）
                </div>
              </FormItem>
              <FormItem {...formItemLayout} label={' '} colon={false}>
                <Button
                  type="primary"
                  loading={buttonLoading}
                  className={`${prefixCls}-form-btn button-forwards`}
                  onClick={this.onClickSubmit}
                >
                  保存修改
                </Button>
              </FormItem>
            </Form>
          </div>
        </div>
        <EmailTest visible={visible} setModalVisible={this.setModalVisible} />
      </div>
    );
  }
}

MailConfig.propTypes = {
  form: PropTypes.object
};

export default Form.create()(MailConfig);
